﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;

namespace PortUsed
{
    public partial class Form1 : Form
    {
        private Delegate updateView;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            button2.Enabled = false;
            toolStripStatusLabel1.Text = "正在扫描端口";
            toolStripProgressBar1.Value = 0;
            dataGridView1.Rows.Clear();
            new Thread(()=> {
                MonitorTcpConnections();
            }).Start();
        }

        private void MonitorTcpConnections()
        {
            Console.WriteLine("Proto  Local Address          Foreign Address        State           PID");
            List<String> rows = new List<string>();
            List<Scan> scanList = new List<Scan>();
            for (int j = 0; j < 50; j++)
            {
                TcpConnectionTableHelper.MIB_TCPROW_OWNER_PID[] tcpProgressInfoTable = TcpConnectionTableHelper.GetAllTcpConnections();
                int tableRowCount = tcpProgressInfoTable.Length;
                for (int i = 0; i < tableRowCount; i++)
                {
                    TcpConnectionTableHelper.MIB_TCPROW_OWNER_PID row = tcpProgressInfoTable[i];
                    string source = string.Format("{0}:{1}", TcpConnectionTableHelper.GetIpAddress(row.localAddr), row.LocalPort);
                    string dest = string.Format("{0}:{1}", TcpConnectionTableHelper.GetIpAddress(row.remoteAddr), row.RemotePort);
                    string outputRow = string.Format("{0, -7}{1, -23}{2, -23}{3, -16}{4}", "TCP", source, dest, (TCP_CONNECTION_STATE)row.state, row.owningPid);
                    Console.WriteLine("{0, -80}", outputRow);
                    if (!rows.Contains(outputRow))
                    {
                        rows.Add(outputRow);
                        Scan scan = new Scan("TCP", source, dest, (TCP_CONNECTION_STATE)row.state, row.owningPid);
                        scanList.Add(scan);
                    }
                }
                Thread.Sleep(100);
                this.Invoke(new Action(()=> {
                    toolStripProgressBar1.Increment(2);
                }));
               
            }

            this.Invoke(new Action(()=> {
                foreach (var item in scanList)
                {
                    int index = dataGridView1.Rows.Add();
                    dataGridView1.Rows[index].Cells[0].Value = item.type;
                    dataGridView1.Rows[index].Cells[1].Value = item.source;
                    dataGridView1.Rows[index].Cells[2].Value = item.dest;
                    dataGridView1.Rows[index].Cells[3].Value = item.state;
                    dataGridView1.Rows[index].Cells[4].Value = item.owningPid;
                }
                button1.Enabled = true;
                button2.Enabled = true;

                toolStripStatusLabel1.Text = "扫描完成";
                toolStripProgressBar1.Value = 0;
            }));
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            button2.Enabled = false;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            var selectRows = dataGridView1.SelectedRows;
            if(selectRows.Count == 0)
            {
                return;
            }

            int pid = (int)selectRows[0].Cells[4].Value;
            Process process = Process.GetProcessById(pid);
            if(process == null)
            {
                MessageBox.Show("获取进程相关信息失败,请尝试重新操作");
                return;
            }

            try
            {
                process.Kill();
                process.WaitForExit();
                process.Close();
                dataGridView1.Rows.Remove(selectRows[0]);
                MessageBox.Show("操作成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message ,"结束进程失败");
            }
        }
    }
}
